// service/issue/issue.js
const app = getApp()
import http from "../../utils/http"
import util from "../../utils/util"
Page({

  /**
   * 页面的初始数据
   */
  data: {
    safeBottom: `30px`,
    cateShow: false,
    skillcate: [],
    columns: [],
    cateName: '',
    tags: [],
    cate: [],
    skill_cate_ids: '',
    name: '',
    tag_name: '',
    to_shop: ['door'],
    image: '',
    images: [],
    spec_type: 0,
    response_hour: '',
    is_travel: 0,
    flow_path_images: [],
    illustrate_images: [],
    category_id: '',
    two_category_id: '',
    price: '',
    cost_seconds: '',
    choose_skill_type: 0,
    spu: [{
      name: '',
      info: [{
        name: ''
      }]
    }],
    sku: [],
    addGoods: [{
      name: '',
      price: '',
      cost_seconds: ''
    }],
    checked: false,
    checkJZflag:false,//是否家政类项目，false为否，true为是，非家政类项目不需维护服务人员类型
    id: '',
    start_hour: '',
    end_hour: '',
    action: '',
    token: ''
  },
  check(e) {
    this.setData({
      checked: e.detail
    })
  },
  checkJZflag(e) {
    this.setData({
      checkJZflag: e.detail,
      
    });
    var life_flag=this.data.checkJZflag?0:1;
    http.post('category/getlist', {
      type: 'all',
      life_flag:life_flag
    }, true).then(res => {
      // let column1 = res.data.map(value => {return value.label})
      // let column1 = res.data.map(value => {return value.label})
      let columns = [{
          values: res.data,
          className: 'column1',
        },
        {
          values: res.data[0].children,
          className: 'column2',
          defaultIndex: 2,
        },
      ]
      this.setData({
        cate: res.data,
        columns: columns,
        cateName:''
      })
    })
  },
  pushtags(e) {
    if (this.data.tags.includes(e.currentTarget.dataset.id)) {
      this.data.tags = this.data.tags.filter(item => item != e.currentTarget.dataset.id)
    } else {
      this.data.tags.push(e.currentTarget.dataset.id)
    }
    this.setData({
      tags: this.data.tags,
      skill_cate_ids: this.data.tags.join(','),
    })
  },
  addSpuName() {
    this.data.spu.push({
        name: '',
        info: [{
          name: ''
        }]
      }),
      this.setData({
        spu: this.data.spu
      })
  },
  addAddgoods() {
    this.data.addGoods.push({
      name: '',
      price: '',
      cost_seconds: ''
    })
    this.setData({
      addGoods: this.data.addGoods
    })
  },
  delSpu(e) {
    let index = e.currentTarget.dataset.index
    this.data.spu.splice(index, 1)
    this.setData({
      spu: this.data.spu
    })
  },
  delSpuInfo(e) {
    let index = e.currentTarget.dataset.index
    let i = e.currentTarget.dataset.i
    this.data.spu[index].info.splice(i, 1)
    this.setData({
      spu: this.data.spu
    })
  },
  delAddgoods(e) {
    let index = e.currentTarget.dataset.index
    this.data.addGoods.splice(index, 1)
    this.setData({
      addGoods: this.data.addGoods
    })
  },
  addSkuName(e) {
    this.data.spu[e.currentTarget.dataset.index].info.push({
      name: ''
    })
    this.setData({
      spu: this.data.spu
    })
  },
  changeSpu(e) {
    this.data.spu[e.currentTarget.dataset.index].name = e.detail.value
    this.setData({
      spu: this.data.spu
    })
  },
  changeSpu1(e) {
    this.data.spu[e.currentTarget.dataset.index].info[e.currentTarget.dataset.i].name = e.detail.value
    this.setData({
      spu: this.data.spu
    })
  },
  addCost(e) {
    this.data.sku[e.currentTarget.dataset.index].cost_seconds = e.detail.value
    this.setData({
      sku: this.data.sku
    })
  },
  addgoodsName(e) {
    this.data.addGoods[e.currentTarget.dataset.index].name = e.detail.value
    this.setData({
      addGoods: this.data.addGoods
    })
  },
  addgoodsCost(e) {
    this.data.addGoods[e.currentTarget.dataset.index].cost_seconds = e.detail.value
    this.setData({
      addGoods: this.data.addGoods
    })
  },
  addgoodsPrice(e) {
    this.data.addGoods[e.currentTarget.dataset.index].price = e.detail.value
    this.setData({
      addGoods: this.data.addGoods
    })
  },
  addPrice(e) {
    this.data.sku[e.currentTarget.dataset.index].price = e.detail.value
    this.setData({
      sku: this.data.sku
    })
  },
  save() {
    if (this.data.image === '') return util.toast('请上传项目封面图')
    if (this.data.images.length ==  0) return util.toast('请上传项目轮播图')
    if (this.data.name.trim() === '') return util.toast('请输入项目标题')
    if (this.data.tag_name.trim() === '') return util.toast('请输入项目标签')
    if(this.data.to_shop.length == 0) return util.toast('项目类型至少选择一种')
    // if(this.data.flow_path_images.length == 0) return util.toast('请上传服务流程图')
    // if(this.data.illustrate_images.length == 0) return util.toast('请上传服务详情图')
    if(this.data.cateName.trim() === '') return util.toast('请选择所属项目分类')
    if(this.data.checkJZflag && this.data.skill_cate_ids.trim() === '') return util.toast('请选择服务人员类别')
    if(this.data.response_hour < 0) return util.toast('请输入最快响应时间')
    if(this.data.choose_skill_type == 0 && (this.data.start_hour < 0 || this.data.start_hour > 24)) return util.toast('请输入0-24的可约开始时间')
    if(this.data.choose_skill_type == 0 && (this.data.end_hour < 0 || this.data.end_hour > 24)) return util.toast('请输入0-24的可约结束时间')
    if(this.data.price < 0) return util.toast('请输入项目价格')
    if(this.data.spec_type == 1 && this.data.sku.length == 0) return util.toast('请输入正确的规格内容')
    let finish = true
    if(this.data.spec_type == 1){
      for(let i=0; i < this.data.spu.length; i++){
        if(this.data.spu[i].name.trim() === ''){
          finish = false
          break
        }
      }
      for(let i=0; i < this.data.sku.length; i++){
        if(this.data.sku[i].name.trim() === '' || this.data.sku[i].cost_seconds <= 0 || this.data.sku[i].price <= 0){
          finish = false
          break
        }
      }
    }
    if(!finish) return util.toast('请输入正确的规格内容')

    let add = true
    if(this.data.checked){
      for(let i=0; i < this.data.addGoods.length; i++){
        if(this.data.addGoods[i].name.trim() === '' || this.data.addGoods[i].cost_seconds <= 0 || this.data.addGoods[i].price <= 0){
          add = false
          break
        }
      }
    }
    if(!add) return util.toast('请输入正确的加项内容')

    let data = {
      name: this.data.name,
      tag_name: this.data.tag_name,
      to_shop: this.data.to_shop.join(','),
      image: this.data.image,
      images: this.data.images.join(','),
      spec_type: this.data.spec_type,
      response_hour: this.data.response_hour,
      is_travel: this.data.is_travel,
      flow_path_images: this.data.flow_path_images.join(','),
      illustrate_images: this.data.illustrate_images.join(','),
      category_id: this.data.category_id,
      two_category_id: this.data.two_category_id,
      skill_cate_ids: this.data.skill_cate_ids,
      price: this.data.price,
      start_hour: this.data.start_hour,
      end_hour: this.data.end_hour,
      cost_seconds: this.data.cost_seconds,
      choose_skill_type: this.data.choose_skill_type,
      life_flag:!this.data.checkJZflag,
      spu: JSON.stringify(this.data.spu),
      sku: JSON.stringify(this.data.sku),
    }
    if (this.data.checked) {
      data['addGoods'] = JSON.stringify(this.data.addGoods)
    }
    if (this.data.id) {
      data['id'] = this.data.id
    }
    http.post(this.data.id ? 'goods/shopeditgoods' : 'goods/shopaddgoods' , data, true).then(res => {
      util.toast(res.msg)
      setTimeout(()=>{
        util.back()
      },1000)
    })
  },
  showCate() {
    this.setData({
      cateShow: true
    })
  },
  getInfo() {
    if (this.data.id) {
      http.get('goods/shopgoodsinfo', {
        id: this.data.id
      }, true).then(res => {
        let arr = res.data.skill_cate_ids.split(',').map(value => {return Number(value)})
        let spu = [],sku =[]
        if(res.data.spec_type === 1){
           spu = res.data.spu.map(value => {
            delete value.id
            delete value.goods_id
            delete value.createtime
            delete value.updatetime
            delete value.status
            let info = value.skudetail.split(',')
            value.info = info.map(val => {
              return {name: val}
            })
            return value
          })
  
           sku = res.data.sku.map(value => {
            delete value.id
            delete value.goods_id
            delete value.salenums
            delete value.createtime
            delete value.updatetime
            delete value.status
            return value
          })
        }
        
        this.setData({
          cateName: res.data.category_name + '/' + res.data.two_category_name,
          tags: arr,
          skill_cate_ids: res.data.skill_cate_ids,
          name: res.data.name,
          tag_name: res.data.tag_name,
          to_shop: res.data.to_shop.split(','),
          image: res.data.image,
          images: res.data.images.split(','),
          spec_type: res.data.spec_type,
          response_hour: res.data.response_hour,
          is_travel: res.data.is_travel,
          flow_path_images: res.data.flow_path_images.split(','),
          illustrate_images: res.data.illustrate_images.split(','),
          category_id: res.data.category_id,
          two_category_id: res.data.two_category_id,
          price: res.data.price,
          start_hour: res.data.start_hour,
          end_hour: res.data.end_hour,
          cost_seconds: res.data.cost_seconds,
          choose_skill_type: res.data.choose_skill_type,
          spu: res.data.spec_type === 1 ? spu : [{
            name: '',
            info: [{
              name: ''
            }]
          }],
          sku: res.data.spec_type === 1 ? sku : [],
          addGoods: res.data.addGoods,
          checked: res.data.addGoods.length > 0
        })
        http.get('shop/shopindex').then(res => {
          this.setData({
            action: res.data.shopInfo.to_shop
          })
          if(this.data.action === 0){
            this.setData({
              to_shop: ['door']
            })
          }
        })
      })
    }else{
      http.get('shop/shopindex').then(res => {
        this.setData({
          action: res.data.shopInfo.to_shop
        })
      })
    }
    http.post('skillcate/getlist', '', true).then(res => {

      this.setData({
        skillcate: res.data
      })
    })
    var life_flag=this.data.checkJZflag?0:1;
    http.post('category/getlist', {
      type: 'all',
      life_flag:life_flag
    }, true).then(res => {
      // let column1 = res.data.map(value => {return value.label})
      // let column1 = res.data.map(value => {return value.label})
      let columns = [{
          values: res.data,
          className: 'column1',
        },
        {
          values: res.data[0].children,
          className: 'column2',
          defaultIndex: 2,
        },
      ]
      this.setData({
        cate: res.data,
        columns: columns
      })
    })

    
  },
  onChange(e) {
    const {
      picker,
      value,
      index
    } = e.detail;
    picker.setColumnValues(1, value[0].children);
  },
  confirm(e) {
    let index = e.detail.index
    if(this.data.cate[index[0]].children.length>0){
      this.setData({
        cateName: this.data.cate[index[0]].label + '/' + this.data.cate[index[0]].children[index[1]].label,
        category_id: this.data.cate[index[0]].id,
        two_category_id: this.data.cate[index[0]].children[index[1]].id,
        cateShow: false
      })
    }else {
      this.setData({
        cateName: this.data.cate[index[0]].label,
        category_id: this.data.cate[index[0]].id,
        two_category_id: '',
        cateShow: false
      })
    }
    
  },
  closeCate() {
    this.setData({
      cateShow: false
    })
  },
  chooseImage() {
    http.chooseImg(['album', 'camera'], true).then(res => {
      this.setData({
        image: res.data.url
      })
    })
  },
  delImages(e){
    let index = e.currentTarget.dataset.index
    this.data.images.splice(index,1)
    this.setData({
      images: this.data.images
    })
  },
  delFlow(e){
    let index = e.currentTarget.dataset.index
    this.data.flow_path_images.splice(index,1)
    this.setData({
      flow_path_images: this.data.flow_path_images
    })
  },
  delIll(e){
    let index = e.currentTarget.dataset.index
    this.data.illustrate_images.splice(index,1)
    this.setData({
      illustrate_images: this.data.illustrate_images
    })
  },
  chooseImages(e) {
    let index = e.currentTarget.dataset.index
    http.chooseImg(['album', 'camera'], true).then(res => {
      let arr = this.data.images;
      if(index){
        arr.splice(index,1,res.data.url)
      }else {
        arr.push(res.data.url)
      }
      
      this.setData({
        images: arr
      })
    })
  },
  chooseFlow(e) {
    let index = e.currentTarget.dataset.index
    http.chooseImg(['album', 'camera'], true).then(res => {
      let arr = this.data.flow_path_images;
      if(index){
        arr.splice(index,1,res.data.url)
      }else {
        arr.push(res.data.url)
      }
      this.setData({
        flow_path_images: arr
      })
    })
  },
  chooseIll(e) {
    let index = e.currentTarget.dataset.index
    http.chooseImg(['album', 'camera'], true).then(res => {
      let arr = this.data.illustrate_images;
      if(index){
        arr.splice(index,1,res.data.url)
      }else {
        arr.push(res.data.url)
      }
      this.setData({
        illustrate_images: arr
      })
    })
  },
  setShop(e) {
    let type = e.currentTarget.dataset.type
    let index = this.data.to_shop.indexOf(type)
    if (index === -1) {
      this.data.to_shop.push(type)

    } else {
      this.data.to_shop.splice(index, 1)
    }
    if(this.data.to_shop.indexOf('door') == -1){
      this.data.choose_skill_type = 0
    }
    this.setData({
      to_shop: this.data.to_shop,
      choose_skill_type: this.data.choose_skill_type
    })
  },
  setTravel(e) {
    this.setData({
      is_travel: e.currentTarget.dataset.type
    })
  },
  setSkill(e) {
    this.setData({
      choose_skill_type: e.currentTarget.dataset.type
    })
  },
  setSpec(e) {
    this.setData({
      spec_type: e.currentTarget.dataset.type
    })
  },

  setName(e) {
    this.setData({
      name: e.detail.value
    })
  },
  setSeconds(e) {
    this.setData({
      cost_seconds: e.detail.value
    })
  },
  setStart(e) {
    this.setData({
      start_hour: e.detail.value
    })
  },
  setEnd(e) {
    this.setData({
      end_hour: e.detail.value
    })
  },
  setPrice(e) {
    this.setData({
      price: e.detail.value
    })
  },
  setResponse(e) {
    this.setData({
      response_hour: e.detail.value
    })
  },
  setTag(e) {
    this.setData({
      tag_name: e.detail.value
    })
  },

  combination(spu) {
    let result = [
      []
    ];
    spu.map(a => {
      var res = [];
      result.map(b => {
        a.info.map(c => {

          res.push([...b, c.name])
        })
      })

      result = res;
    })
    return result
  },
  watch: {
    spu: {
      deep: true,
      handler() {
        let sku = this.combination(this.data.spu)
        let arr = [];
        for (let i = 0; i < sku.length; i++) {
          arr.push({
            name: sku[i].join(','),
            cost_seconds: '',
            price: ''
          })
        }
        this.setData({
          sku: arr
        })
      }
    },
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const high = app.globalData.safeBottom
    this.setData({
      safeBottom: `${high}px`,
      id: options.id || '',
      token: wx.getStorageSync('token')
    })
    util.setWatcher(this)
    this.getInfo()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})